package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Vector;

import entidades.Disco;

public class DiscosDAO {

	public static void cargarDiscos(Vector<Disco> listaDiscos) throws SQLException {
	
		if (listaDiscos.size() != 0) {
			Connection conexion = PrincipalDAO.connect();
		
			String sql ="INSERT INTO `discos` ( " +
						"	`id` , `idGrupo` ,`nombreDisco` " +
						" ) " +
						" VALUES ( ?, ?, ? )";
		
			PreparedStatement prep = conexion.prepareStatement(sql);

			
			for (int i=0; i < listaDiscos.size(); i++) {
				prep.setInt(1, listaDiscos.elementAt(i).getId());
				prep.setInt(2, listaDiscos.elementAt(i).getIdGrupo());
				prep.setString(3, listaDiscos.elementAt(i).getTitle());
				prep.addBatch();
			}
			
			conexion.setAutoCommit(false);
			prep.executeBatch();
			conexion.setAutoCommit(true);
			conexion.close();
		}
	
	}

	public static void crearTablaDiscos() throws SQLException {
		
		Connection conexion = PrincipalDAO.connect();
		Statement statement = conexion.createStatement();
		
		statement.execute("DROP TABLE  IF EXISTS `discos`");
		String sql =" CREATE TABLE discos ( " +
					" `id` INT NOT NULL , " +
					" `idGrupo` INT NOT NULL , " +
					" `nombreDisco` VARCHAR( 100 ) NOT NULL ,PRIMARY KEY ( `id` ) ,UNIQUE (`nombreDisco`) "  +
					" ) ;	" ; 
		
		//System.out.println(sql);
		statement.executeUpdate(sql);
		conexion.close();
	
	}

	public static int getIdUltimoDisco() throws SQLException {
		Connection conexion = PrincipalDAO.connect();
		Statement statement = conexion.createStatement();
		
		String sql =" SELECT MAX(`id`) AS idFinal " +
					" FROM discos ";
		
		//System.out.println(sql);
		ResultSet rs = statement.executeQuery(sql);
		Integer maxId;
		
		if (rs.next()) {
			maxId = rs.getInt("idFinal");
			System.out.println("Maximo id disco : " + maxId);
		}
		else 
			maxId = 0;			
		
		conexion.close();
		rs.close();
		return maxId;
	}

	public static Hashtable<String, Integer> discosYaCargados() throws SQLException {
		Hashtable<String, Integer> idGrupo = new Hashtable<String, Integer>();

		Connection conexion = PrincipalDAO.connect();
		Statement statement = conexion.createStatement();
		
		String sql =" SELECT * " +
					" FROM discos ";
		
		//System.out.println(sql);
		ResultSet rs = statement.executeQuery(sql);
		Integer id;
		String nombre;
		
		while (rs.next()) {
			id = rs.getInt("id");
			nombre = rs.getString("nombreDisco");
			//System.out.println(nombre);
			idGrupo.put(nombre, id);
		}
		
		conexion.close();
		rs.close();
		
		return idGrupo;
	}
}
